<?php

namespace app\admin\model\system;

use app\admin\service\curd\GenService;
use app\common\model\TimeModel;
use think\facade\Db;

class SystemGenTable extends TimeModel
{
    public static function SelectDbTableList($page, $limit, $where, $sort)
    {
        $model = Db::table('information_schema.tables');

        $model->WhereRaw("table_schema = (select database())");
        //时间转换为Y-m-d H:i:s
        foreach ($where as $k => $item) {
            if ($item[0] == 'create_time' || $item[0] == 'update_time') {
                $where[$k][2] = date('Y-m-d H:i:s', $item[2]);
            }
        }
        $count = $model->where($where)->count();
        $list = $model->where($where)
            ->page($page, $limit)
            ->order($sort)
            ->select()->toArray();
        //返回字段名转小写
        if (is_array($list) && count($list)) {
            foreach($list as $k => $item) {
                $temp = [];
                foreach($item as $key => $value) {
                    $temp[strtolower($key)] = $value;
                }
                $list[$k] = $temp;
            }
        }

        return [$count, $list];
    }

    public static function SelectDbTableListByNames($tableNames)
    {
        $model = Db::table('information_schema.tables');

        $model->WhereRaw("table_schema = (select database())");
        if (count($tableNames)) {
            $model->WhereIn("table_name", $tableNames);
        }
        return $model->select();
    }


    //导入表结构
    public static function ImportGenTable($tableList, $operName)
    {
        if (empty($tableList) || empty($operName)) return;
        foreach ($tableList as $table) {
            $table = json_decode(json_encode($table));
            $tableName = $table->TABLE_NAME;
            $new_table = static::InitTable($table, $operName);
            $tmpid = self::insertGetId($new_table);
            if ($tmpid <= 0) {
                return;
            }
            $new_table['id'] = $tmpid;
            $genTableColumns = SystemGenTableColumn::SelectDbTableColumnsByName($tableName)->toArray();
            foreach ($genTableColumns as $column) {
                if (isset($column['COLUMN_NAME'])) {
                    $column['column_name'] = $column['COLUMN_NAME'];
                    unset($column['COLUMN_NAME']);
                }
                if (isset($column['COLUMN_COMMENT'])) {
                    $column['column_comment'] = $column['COLUMN_COMMENT'];
                    unset($column['COLUMN_COMMENT']);
                }
                if (isset($column['COLUMN_TYPE'])) {
                    $column['column_type'] = $column['COLUMN_TYPE'];
                    unset($column['COLUMN_TYPE']);
                }
                $column = json_decode(json_encode($column));
                static::InitColumnField($column, $new_table);
                SystemGenTableColumn::insert(json_decode(json_encode($column), true));
            }
        }
    }

    //初始化表信息
    public static function InitTable($table, $operName)
    {
        $new_table = [];
        $new_table['table_name'] = $table->TABLE_NAME;
        $new_table['table_comment'] = $table->TABLE_COMMENT;
        $new_table['class_name'] = static::ConvertClassName($table->TABLE_NAME);
        $new_table['package_name'] = config('admin.gen.packageName');
        $new_table['module_name'] = config('admin.gen.moduleName');
        $new_table['controller_name'] = static::GetBusinessName($table->TABLE_NAME);
        $new_table['model_name'] = static::GetBusinessName($table->TABLE_NAME);
        $new_table['function_author'] = config('admin.gen.author');
        $new_table['create_by'] = $operName;
        $new_table['tpl_category'] = "crud";
        $new_table['create_time'] = time();
        return $new_table;
    }

    //表名转换成类名
    public static function ConvertClassName($tableName)
    {
        $autoRemovePre = config('admin.gen.autoRemovePre');
        $tablePrefix = config('admin.gen.tablePrefix');
        if ($autoRemovePre && $tablePrefix != "") {
            $searchList = explode(",", $tablePrefix);
            foreach ($searchList as $str) {
                $tableName = str_replace($str, "", $tableName);
            }
        }
        return $tableName;
    }

    //获取业务名
    public static function GetBusinessName($tableName)
    {
        $lastIndex = strrpos($tableName, "_");
        if ($lastIndex === false) $lastIndex = -1;
        $businessName = substr($tableName, $lastIndex + 1);
        return $businessName;
    }

    //初始化列属性字段
    public static function InitColumnField($column, $table)
    {
        $dataType = static::GetDbType($column->column_type);
        $columnName = $column->column_name;
        $column->table_id = $table['id'];
        $column->create_by = $table['create_by'];
        //设置字段名
        $column->go_field = $columnName;
        $column->html_field = $columnName;
        $column->go_type = "string";

        if (in_array($dataType, SystemGenTableColumn::$COLUMNTYPE_STR)) {
            //字段为字符串类型
            $column->go_type = "string";
            if ($dataType == "text" || $dataType == "tinytext" || $dataType == "mediumtext" || $dataType == "longtext") {
                $column->html_type = "textarea";
            } else {
                $columnLength = static::GetColumnLength($dataType);
                if ($columnLength >= 500) {
                    $column->html_type = "textarea";
                } else {
                    $column->html_type = "text";
                }
            }
        } else if (in_array($dataType, SystemGenTableColumn::$COLUMNTYPE_TIME)) {
            //字段为时间类型
            $column->go_type = "Time";
            $column->html_type = "date";
        } else if (in_array($dataType, SystemGenTableColumn::$COLUMNTYPE_NUMBER)) {
            //字段为数字类型
            $column->html_type = "text";
            // 如果是浮点型
            $tmp = trim(str_replace('unsigned', '', $column->column_type));
            if ($tmp == "float" || $tmp == "double" || strpos($tmp, '(')) {
                $column->go_type = "float64";
            } elseif ($tmp == 'bigint') {
                $column->go_type = "int64";
            } else {
                $column->go_type = "int";
            }
        }
        //新增字段
        if ($columnName == "create_by" || $columnName == "create_time" || $columnName == "update_by" || $columnName == "update_time" || $columnName == "delete_time") {
            $column->is_required = "0";
            $column->is_insert = "0";
        } else {
            $column->is_required = "0";
            $column->is_insert = "1";
            if (strpos($columnName, "name") !== false || strpos($columnName, "status") !== false) {
                $column->is_required = "1";
            }
        }

        // 编辑字段
        if (!in_array($columnName, SystemGenTableColumn::$COLUMNNAME_NOT_EDIT)) {
            if ($column->is_pk == "1") {
                $column->is_edit = "0";
            } else {
                $column->is_edit = "1";
            }
        } else {
            $column->is_edit = "0";
        }
        // 列表字段
        if (!in_array($columnName, SystemGenTableColumn::$COLUMNNAME_NOT_LIST)) {
            $column->is_list = "1";
        } else {
            $column->is_list = "0";
        }
        // 查询字段
        if (!in_array($columnName, SystemGenTableColumn::$COLUMNNAME_NOT_QUERY)) {
            $column->is_query = "1";
        } else {
            $column->is_query = "0";
        }

        // 查询字段类型
        if (substr($columnName, -4) == 'name') {
            $column->query_type = "LIKE";
        } else {
            $column->query_type = "EQ";
        }
        if ($column->go_type == 'string') {
            $column->query_type = "LIKE";
        }

        // 状态字段设置单选框
        if (substr($columnName, -6) == 'status') {
            $column->html_type = "radio";
        } else if (substr($columnName, -4) == 'type' || substr($columnName, -3) == 'sex') {
            // 类型&性别字段设置下拉框
            $column->html_type = "select";
        }
        if ($column->is_pk == "1") {
            $column->is_insert = "0";
        }

        $_column = [
            'field' => $column->column_name,
            'type' => $column->column_type,
            'comment' => $column->column_comment,
        ];
        (new GenService())->buildColum($_column);
        $column->html_type = $_column['formType'] ?? 'text';
        $column->column_comment = $_column['comment'] ?? $_column['field'];
        $column->dict_type = $_column['data_list'] ?? '';
    }

    //获取数据库类型字段
    public static function GetDbType($columnType)
    {
        if (strpos($columnType, "(") > 0) {
            return substr($columnType, 0, strpos($columnType, "("));
        } else {
            return $columnType;
        }
    }

    //获取字段长度
    public static function GetColumnLength($columnType)
    {
        $start = strpos($columnType, "(");
        $end = strpos($columnType, ")");
        $result = substr($columnType, $start + 1, $end - $start);
        return intval($result);
    }
}